package cn.wsalix.shiro.filter;

import java.io.IOException;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.apache.shiro.web.util.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.anlaser.admin.BaseUser;
import cn.wsalix.admin.entity.SysUser;
import cn.wsalix.admin.service.UserService;
import cn.wsalix.shiro.token.CaptchaToken;

public class IdFormAuthenticationFilter extends FormAuthenticationFilter {
	private static final Logger logger = LoggerFactory
			.getLogger(IdFormAuthenticationFilter.class);
	private String contentType = "ContentType";
	private String jsonContentType = "application/json;charset=UTF-8";
	private static final Logger log = LoggerFactory
			.getLogger(IdFormAuthenticationFilter.class);
	private UserService userService;

	/*
	 * 主要是针对登入成功的处理方法。对于请求头是AJAX的之间返回JSON字符串。
	 */
	@Override
	protected boolean onLoginSuccess(AuthenticationToken token,
			Subject subject, ServletRequest request, ServletResponse response)
			throws Exception {
		Subject currentUser = SecurityUtils.getSubject();
		BaseUser baseUser = (BaseUser) currentUser.getPrincipal();
		Session session = currentUser.getSession();
		SysUser user = userService.findById(baseUser.getId());
		session.setAttribute("currUser", user);
		session.setAttribute("currInfo", user.getUserInfo());
		session.setAttribute("currCenter", user.getUserCenter());
		logger.info(getSuccessUrl());
		issueSuccessRedirect(request, response);
		return true;
	}

	/**
	 * 主要是处理登入失败的方法
	 */
	@Override
	protected boolean onLoginFailure(AuthenticationToken token,
			AuthenticationException e, ServletRequest request,
			ServletResponse response) {
		try {
			request.setAttribute("e", e);
			redirectToLogin(request, response);
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		return false;
	}

	/**
	 * 所有请求都会经过的方法。
	 */
	@Override
	protected boolean onAccessDenied(ServletRequest request,
			ServletResponse response) throws Exception {
		// showPara(request,response);
		HttpServletRequest httpServletRequest = (HttpServletRequest) request;
		String reqContentType = httpServletRequest.getHeader(contentType);

		if (isLoginRequest(request, response)) {
			if (isLoginSubmission(request, response)) {
				if (log.isTraceEnabled()) {
					log.trace("Login submission detected.  Attempting to execute login.");
				}
				return executeLogin(request, response);
			} else {
				if (log.isTraceEnabled()) {
					log.trace("Login page view.");
				}
				// allow them to see the login page ;)
				// saveRequestAndRedirectToLogin(request, response);
				return true;
			}
		} else {
			redirectToLogin(request, response);
			return false;
		}
	}

	protected AuthenticationToken createToken(ServletRequest request,
			ServletResponse response) {
		String username = WebUtils.getCleanParam(request, "id_login_username");
		String password = WebUtils.getCleanParam(request, "id_login_password");
		String rememberMe = WebUtils.getCleanParam(request, "remember");
		String shopId = WebUtils.getCleanParam(request, "shopId");
		if (username == null || password == null) {
			return null;
		}
		String host = getHost(request);
		CaptchaToken upToken = new CaptchaToken();
		upToken.setUsername(username);
		upToken.setPassword(password.toCharArray());
		upToken.setShopId(shopId);
		if (rememberMe != null) {
			upToken.setRememberMe(rememberMe.equals("on"));
		}
		upToken.setHost(host);
		return upToken;
		// return createToken(username, password, true, host);
	}

	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

}
